<template>
  <el-container class="layout-container">
    <el-aside width="200px" class="sidebar">
      <div class="logo">
        <h3>RBAC系统</h3>
      </div>
      
      <el-menu
        :default-active="$route.path"
        class="sidebar-menu"
        router
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
      >
        <el-menu-item index="/">
          <el-icon><House /></el-icon>
          <span>首页</span>
        </el-menu-item>
        
        <el-sub-menu index="/system" v-if="hasSystemPermission">
          <template #title>
            <el-icon><Setting /></el-icon>
            <span>系统管理</span>
          </template>
          
          <el-menu-item index="/user" v-if="hasUserPermission">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </el-menu-item>
          
          <el-menu-item index="/role" v-if="hasRolePermission">
            <el-icon><UserFilled /></el-icon>
            <span>角色管理</span>
          </el-menu-item>
          
          <el-menu-item index="/permission" v-if="hasPermissionPermission">
            <el-icon><Key /></el-icon>
            <span>权限管理</span>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>
    
    <el-container>
      <el-header class="header">
        <div class="header-left">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item>首页</el-breadcrumb-item>
            <el-breadcrumb-item v-if="currentPageTitle !== '首页'">{{ currentPageTitle }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-avatar :size="32" :src="avatarUrl">
                {{ user.realName?.charAt(0) || user.username?.charAt(0) }}
              </el-avatar>
              <span class="username">{{ user.realName || user.username }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      
      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessageBox, ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const user = computed(() => authStore.user)

// 权限检查
const hasSystemPermission = computed(() => {
  return authStore.hasAnyPermission(['system:user:query', 'system:role:query', 'system:permission:query'])
})

const hasUserPermission = computed(() => {
  return authStore.hasPermission('system:user:query')
})

const hasRolePermission = computed(() => {
  return authStore.hasPermission('system:role:query')
})

const hasPermissionPermission = computed(() => {
  return authStore.hasPermission('system:permission:query')
})

// 当前页面标题
const currentPageTitle = computed(() => {
  return route.meta?.title || '首页'
})

// 头像URL处理
const avatarUrl = computed(() => {
  const v = user.value?.avatar || ''
  console.log('Layout - 原始头像URL:', v) // 调试日志
  
  if (!v) {
    console.log('Layout - 头像URL为空，返回空字符串')
    return ''
  }
  
  let finalUrl = v
  
  // 如果已经是完整的URL，直接返回
  if (v.startsWith('http://') || v.startsWith('https://')) {
    finalUrl = v
  }
  // 如果以/api开头，直接返回
  else if (v.startsWith('/api/')) {
    finalUrl = v
  }
  // 如果以/avatars开头，添加/api前缀
  else if (v.startsWith('/avatars/')) {
    finalUrl = '/api' + v
  }
  // 其他情况，直接返回
  else {
    finalUrl = v
  }
  
  console.log('Layout - 处理后的头像URL:', finalUrl) // 调试日志
  return finalUrl
})

// 全局错误处理
const handleGlobalError = (event) => {
  console.error('全局错误:', event.error)
  
  // 如果是401错误，直接跳转到登录页
  if (event.error?.response?.status === 401) {
    authStore.logout()
    window.location.href = '/login'
  }
}

// 监听全局错误
onMounted(() => {
  window.addEventListener('error', handleGlobalError)
  window.addEventListener('unhandledrejection', (event) => {
    if (event.reason?.response?.status === 401) {
      authStore.logout()
      window.location.href = '/login'
    }
  })
})

onUnmounted(() => {
  window.removeEventListener('error', handleGlobalError)
})

const handleCommand = async (command) => {
  if (command === 'logout') {
    try {
      await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      // 等待logout完成后再跳转
      await authStore.logout()
      
      // 使用setTimeout确保状态清理完成后再跳转
      setTimeout(() => {
        window.location.href = '/login'
      }, 100)
      
    } catch (error) {
      console.log('取消登出或登出失败:', error)
    }
  } else if (command === 'profile') {
    router.push('/profile')
    ElMessage.success('已进入个人信息')
  }
}
</script>

<style scoped>
.layout-container {
  height: 100vh;
}

.sidebar {
  background-color: #304156;
  color: white;
}

.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #435266;
}

.logo h3 {
  color: white;
  margin: 0;
}

.sidebar-menu {
  border: none;
}

.header {
  background-color: white;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.header-left { display: flex; align-items: center; }
.header-right { display: flex; align-items: center; }

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}
.user-info:hover { background-color: #f5f5f5; }
.username { margin: 0 8px; color: #333; }

.main-content { background-color: #f0f2f5; padding: 20px; }
</style> 